using System.Runtime.InteropServices;


namespace System {
  public class WindowProcessStream : ProcessStream {
    private IntPtr m_ProcessID;
    private IntPtr m_Window;

    public WindowProcessStream( IntPtr window ) {
      this.m_Window = window;
    }

    public IntPtr Window {
      get { return this.m_Window; }
      set {
        this.m_Window = value;
        this.m_ProcessID = IntPtr.Zero;
      }
    }

    public override IntPtr ProcessID {
      get {
        if ( IsWindow( this.m_Window ) && this.m_ProcessID != IntPtr.Zero )
          return this.m_ProcessID;

        GetWindowThreadProcessId( this.m_Window, ref this.m_ProcessID );

        return this.m_ProcessID;
      }
    }

    [DllImport( "user32.dll" )]
    private static extern bool IsWindow( IntPtr window );

    [DllImport( "User32" )]
    private static extern int GetWindowThreadProcessId( IntPtr window, ref IntPtr processID );
  }
}